package com.mytest.leetcode;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
@Slf4j
public class Solution6 {

    public static void main(String[] args) {
        Solution6 solution = new Solution6();
        String s = "PAYPALISHIRING";
        log.info("{}", solution.convert(s, 3));
    }

    public String convert(String s, int numRows) {
        int length = s.length();
        char [] chars = s.toCharArray();
        // 一组所用字符长度
        int arrays = 2*(numRows -1);
        if (arrays ==0) {
            return s;
        }
        // 有几组
        int group = length/arrays;
        // 取余
        int remainder = length%arrays;
        // 第二数组长度
        int row = remainder/numRows + remainder%numRows+ group*(numRows-1);

        char[][] result = new char[numRows][row];
        for(int i=0 ,x = 0, y = 0;i< chars.length;i++) {
//            log.info("[{},{}]", x, y);
            result[x][y] = chars[i];
            if (i % arrays < numRows - 1) {
                ++x; // 向下移动
            } else {
                --x;
                ++y; // 向右上移动
            }
        }
        StringBuffer str = new StringBuffer();
        for (char[] rows : result) {
            for (char ch : rows) {
                if (ch != 0) {
                    str.append(ch);
                }
            }
        }
        return str.toString();
    }


    public String convert1(String s, int numRows) {
        int n = s.length(), r = numRows;
        if (r == 1 || r >= n) {
            return s;
        }
        StringBuffer[] mat = new StringBuffer[r];
        for (int i = 0; i < r; ++i) {
            mat[i] = new StringBuffer();
        }
        for (int i = 0, x = 0, t = r * 2 - 2; i < n; ++i) {
            mat[x].append(s.charAt(i));
            if (i % t < r - 1) {
                ++x;
            } else {
                --x;
            }
        }
        StringBuffer ans = new StringBuffer();
        for (StringBuffer row : mat) {
            ans.append(row);
        }
        return ans.toString();
    }
}
